<form class="layui-form" action="{:url()}" method="post" id="editForm">

    {:FormExt::input('模板名', 'name', '', '', 'required', 'lay-verify="required"')}
    {:FormExt::input('排序', 'order', '0', '排序', 'required', 'lay-verify="required|number"')}

    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>部位尺码
            <a href="javascript:void(0)" class="layui-btn layui-btn-primary layui-btn-xs size-add"><i class="layui-icon">&#xe654;</i></a>
<!--            <a href="javascript:void(0)" class="layui-btn layui-btn-primary layui-btn-xs size-tiao-yn"> 跳码尺寸是否生效</a>-->
        </legend>
    </fieldset>
    <div class="layui-form size-list">
        <table class="layui-table">
            <thead>
            <tr>
                <th>部位</th>
                <th>量法</th>
                <th>跳码设置</th>
                <th style="min-width: 180px;">跳码规则</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 0, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 1, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 2, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 3, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 4, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 5, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 6, ''), $sizeNameList)}</th>
                <th>{:Form::select('sizename[]', arrayGet($sizenameArr, 7, ''), $sizeNameList)}</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

    <div class="pop-bottom-bar">
    	<input type="hidden" class="field-id" name="id">
        <button type="submit" class="layui-btn layui-btn-normal" lay-submit="" lay-filter="formSubmit" hisi-data="{pop: true, refresh: true}">提交保存</button>
        <a href="javascript:parent.layui.layer.closeAll();" class="layui-btn layui-btn-primary ml10">取消</a>
    </div>
</form>
<script id="sizeTpl" type="text/html">
    {foreach $partArr as $k => $v}
    <tr>
        <td class="layui_tool_showSelect_{$k}">
        </td>
        <td><input type="text" name="measurement[]" value="{:arrayGet($measurementArr, $k, '')}" autocomplete="off" class="layui-input" lay-verify=""></td>
        <td>
            <a href="javascript:void(0)" onclick="onclickTiaoSize(this)" class="hisi-iframe layui-btn layui-btn-sm " hisi-data="{width: '860px', height: '90%'}" >跳码设置</a>
            <a  href="javascript:void(0)" onclick="onclickTiaoSizeRun(this)" class="layui-btn layui-btn-sm "  >生效</a>
        </td>
        <td class="tiaoSizeContent">-----</td>
        <td><input type="text" name="size[0][]" value="{:arrayGet(arrayGet($sizeArr, 0, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[1][]" value="{:arrayGet(arrayGet($sizeArr, 1, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[2][]" value="{:arrayGet(arrayGet($sizeArr, 2, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[3][]" value="{:arrayGet(arrayGet($sizeArr, 3, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[4][]" value="{:arrayGet(arrayGet($sizeArr, 4, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[5][]" value="{:arrayGet(arrayGet($sizeArr, 5, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[6][]" value="{:arrayGet(arrayGet($sizeArr, 6, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><input type="text" name="size[7][]" value="{:arrayGet(arrayGet($sizeArr, 7, []), $k, '0')}" autocomplete="off" class="layui-input" lay-verify="number"></td>
        <td><a href="javascript:void(0)" class="layui-btn layui-btn-danger layui-btn-sm btn-del"><i class="layui-icon">&#xe640;</i></a></td>
    </tr>
    {/foreach}
</script>

{include file="system@block/layui" /}
<script src="__PUBLIC_JS__/jquery.2.1.4.min.js?v={:config('hisiphp.version')}"></script>
<script src="__PUBLIC_JS__/xm-select/dist/xm-select.js?v={:config('hisiphp.version')}"></script>
<!--<script src="__PUBLIC_JS__/vue@3.2.26/dist/vue.global.js"></script>-->
<script>
    var formData = {:json_encode($formData)};
    var partList = {:json_encode($partList)};
    var partListAll = {:json_encode($partListAll)};
    var xm_select_data = {:json_encode($xm_select_data)};
    var partArrInit = {:json_encode($partArr)};
    var tiaoData=[];
    var allTiaoData={};

    layui.use(['form', 'func', 'jquery', 'upload', 'layer', 'tool'], function() {
        $ = layui.jquery;
        var form = layui.form;
        var laytpl = layui.laytpl,laydate=layui.laydate ,table = layui.table;
        var upload = layui.upload;
        var layer = layui.layer;
        layui.func.assign(formData);

        var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;

        form.verify({
            mimonumber: function(value, item){
                if (value=='') return '';
                if(! reg.test(value)){
                    return '只能填写数字';
                }
            }
        });
        // 添加尺码部位
        $(document).on('click', '.size-add',function(){
            var html='<tr>';
            html += "<td>"+layui.tool.showSelect('part[]', '', partList,'','','lay-filter="partListSelect" onchange="partListSelect(this)" ')+"</td>";
            html += '<td><input type="text" name="measurement[]" value="" autocomplete="off" class="layui-input" lay-verify=""></td>';
            html += '<td>' +
                '<a  href="javascript:void(0)" onclick="onclickTiaoSize(this)" class="hisi-iframe layui-btn layui-btn-sm " hisi-data="{width: \'860px\', height: \'90%\'}" >跳码设置</a>' +
                '<a  href="javascript:void(0)" onclick="onclickTiaoSizeRun(this)" class="layui-btn layui-btn-sm "  >生效</a>' +
                '</td>';
            html += '<td class="tiaoSizeContent">-----</td>';
            html += '<td><input type="text" name="size[0][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[1][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[2][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[3][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[4][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[5][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[6][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><input type="text" name="size[7][]" value="0" autocomplete="off" class="layui-input" lay-verify="number"></td>';
            html += '<td><a href="javascript:void(0)" class="layui-btn layui-btn-danger layui-btn-sm btn-del"><i class="layui-icon">&#xe640;</i></a></td>';
            html += '<tr>';
            $('.size-list table tbody').append(html);
        });
        //尺码部位-初始化
        var content = laytpl($('#sizeTpl').html()).render({data:{}});
        $('.size-list table tbody').append(content);
        $.each(partArrInit, function(i, n){
           var  html = layui.tool.showSelect('part[]', n, partList,'','','lay-filter="partListSelect" onchange="partListSelect(this)" ');
           $('.layui_tool_showSelect_'+i).html(html);
        });

        // 删除条目
        $(document).on('click', '.btn-del',function(){
            $(this).parents('tr').remove();
        });
    });

    // 部位尺码->添加=》部位 选择后设置 量法  --- 并显示跳码规则
    function partListSelect(obj) {
        //2,显示跳码规则
        tiaoSizeContentSet();
        //1,部位 选择后设置 量法
        var temp='';
        $.each( partListAll, function(i, n){
            if($(obj).val()==n.name){
                temp=n.name_ext;
                return ;
            }
        });
        $(obj).parent().parent().find('[name="measurement[]"]').val(temp);
    }

    //跳码设置
    function onclickTiaoSize(obj) {
        var  rows = $(obj).parent().parent().prevAll().length + 1; //行号
        var part=$(obj).parent().parent().find('[name="part[]"]').val();
        $(obj).attr('href',"{:url('mp/Template/tiaoNumEdit')}?tr_num="+rows+'&part='+part);
        $(obj).trigger('click');
    }
    //跳码设置--子函数
    function tiaoNumEdit(d) {
        tiaoData=d;
        allTiaoData[tiaoData.tr_num]=tiaoData;
        //1，自动选择码
        if(tiaoData.selected_type==1){
            th_select_set();
        }
        //2,显示跳码规则
        tiaoSizeContentSet(1);
    }

    //1，自动选择码
    function th_select_set() {
        //计算出所要选择的码
        var arr1 = [];
        for (var i = 0; i < 5; i++) {
            var temp = tiaoData['xm_select_size[]'][i];
            var arr2 = temp.split(',');
            arr1 = arr1.concat(arr2);
        }
        var resval=[];
        $.each(xm_select_data, function(i, n){
            $.each(arr1, function(i2, n2){
                if(n2==n.value){
                    resval.push(n.name);
                }
            });
        });
        resval=uniq(resval);
        //进行选择设置 0-7  $('.size-list').find("div.layui-form-select:eq(1)").find('dl').find('dd[lay-value="XL"]').click();
        for(var i = 0; i < resval.length; i++){
            $('.size-list').find("div.layui-form-select:eq("+i+")").find('dl').find('dd[lay-value="'+resval[i]+'"]').click();
        }
    }

    /**
     * 最简单数组去重法
     */
    function uniq(array){
        var temp = []; //一个新的临时数组
        for(var i = 0; i < array.length; i++){
            if(temp.indexOf(array[i]) == -1){
                temp.push(array[i]);
            }
        }
        return temp;
    }
    //跳码生效
    var sizeRuntemp={};
    function onclickTiaoSizeRun(obj) {
        //1,获跳码规则
        var temp_row = $(obj).parent().parent().prevAll().length + 1; //行号
        sizeRuntemp.row=temp_row;
        if(typeof(allTiaoData[temp_row])=="undefined"){
            layer.msg('没设置跳码规则', {icon: 2,anim: 6});
            return false;
        }
        //2,检查  头部选择的码信息，与，本行有基码大于0 才生效
        //2.1,检查  头部选择的码信息
        var head_select=[];
        for(var i = 0; i < 8; i++){
            var temp=$('.size-list').find('[name="sizename[]"]:eq('+i+')').val();
            if(temp!=''){
                head_select.push(temp);
            }
        }
        sizeRuntemp.head_select=head_select;
        if( sizeRuntemp.head_select.length==0){
            layer.msg('没选择尺码', {icon: 2,anim: 6});
            return false;
        }
        //2.2，本行有基码大于0  $('.size-list').find('tr:eq(1)').find('[name="size[1][]"]').val();
        var size_tr=[];
        var flag=0;
        for(var i = 0; i <= 7; i++){
            var temp=parseFloat( $('.size-list').find('tr:eq('+temp_row+')').find('[name="size['+i+'][]"]').val());
            size_tr.push(temp);
            if(temp>0){
                flag=temp;
            }
        }
        sizeRuntemp.size_tr=size_tr;
        if(flag==0){
            layer.msg('些行基码都为0', {icon: 2,anim: 6});
            return false;
        }
        //3,综合 规则 码  基码 计算出 基码并设置
        set_size_data();
    }
    /**
     * 逻辑计算顺序： 1实际顺序  2位置数   3实际规则   4实际结果  5显示结果
     * 主要参数 xm_select_data  allTiaoData  sizeRuntemp
     * @param obj
     */
    var temp_data={
        wei:{}
        ,rule:{}
        ,temp_res:[]
    };
    function set_size_data() {
        //1,实际顺序 xm_select_data 的data-order就是了，不用计算了
        //2,位置数
        temp_data.wei={};
        $.each(sizeRuntemp.size_tr, function(i, n){
            if( ! $.isEmptyObject(temp_data.wei)){
                return false;
            }
            if( n >0){
                $.each(sizeRuntemp.head_select, function(i2, n2){
                    if(i2==i){
                       temp_data.wei.key=i;
                        temp_data.wei.size_tr=n;
                        temp_data.wei.head_select=n2;
                        return false;
                    }
                });
            }
        });
        $.each(xm_select_data, function(i, n){
            if(n.name==temp_data.wei.head_select){
                xm_select_data[i]['now_start_data']=xm_select_data[i]['now_data']=temp_data.wei.size_tr;
                temp_data.wei.data_order=n['data-order'];
            }
        });
        //3,实际规则
        //3.1, 找出 最大 最小 跳码
        temp_data.temp_res=[];
        $.each(allTiaoData[sizeRuntemp.row]['xm_select_size[]'], function(i, n){
            if(n!=''){
                //找出 最大 最小 跳码
                var temp_res={
                    min:12345678,
                    max:-1,
                    tiao_num: parseFloat( allTiaoData[sizeRuntemp.row]['tiao_num[]'][i])
                };
                var data_order=[];
                var temp=n.split(',');

                $.each(temp, function(i2, n2){
                    $.each(xm_select_data, function(i3, n3){
                        if(n2==n3.value){
                            data_order.push(n3['data-order']);
                            return false;
                        }
                    });
                });
                $.each(data_order, function(i2, n2){
                    if(parseInt(n2)<temp_res.min){
                        temp_res.min=parseInt(n2);
                    }
                    if(parseInt(n2)>temp_res.max){
                        temp_res.max=parseInt(n2);
                    }
                });
                temp_data.temp_res.push(temp_res);
            }
        });
        //3.2, 设置实际规则 到 xm_select_data 里 data-add data-del
        $.each(xm_select_data, function(i2, n2){
            xm_select_data[i2]['data-add']=12345678;
            xm_select_data[i2]['data-del']=12345678;
        });
        $.each(temp_data.temp_res, function(i, n){
            $.each(xm_select_data, function(i2, n2){
                if(n2['data-order']>=n.min && n2['data-order']<=n.max){
                    if(n2['data-order'] < n.max) xm_select_data[i2]['data-add']=n.tiao_num;
                    if(n2['data-order'] > n.min) xm_select_data[i2]['data-del']=n.tiao_num;
                }
            });
        });
        //4,实际结果
        //4.1,加码生效
        $.each(xm_select_data, function(i, n){
           if(temp_data.wei.data_order <n['data-order']){
               xm_select_data[i]['now_data']= xm_select_data[i-1]['now_data']+ xm_select_data[i-1]['data-add'];
           }
        });
        //4.2,减码生效
        xm_select_data.reverse();
        $.each(xm_select_data, function(i, n){
            if(temp_data.wei.data_order > n['data-order']){
                xm_select_data[i]['now_data']= xm_select_data[i-1]['now_data']- xm_select_data[i-1]['data-del'];
            }
        });
        xm_select_data.reverse();
        //5,显示结果
        $.each(sizeRuntemp.head_select, function(i, n){
            $.each(xm_select_data, function(i2, n2){
                if(n2.name==n){
                    if(n2['now_data']<10000000){
                        $('.size-list').find('tr:eq('+sizeRuntemp.row+')').find('[name="size['+i+'][]"]').val(n2['now_data'].toFixed(0));
                    }
                }
            });
        });
    }

    //显示跳码规则
    var allPartTiao={};
    tiaoSizeContentSet(1);
    function tiaoSizeContentSet(flag=0) {
        if(flag==1){
            $.ajax({
                type: "POST",
                url: "{:url('mp/Template/allPartTiao')}",
                data: $("#form33").serialize(),
                dataType:"json",
                success: function(res){
                    allPartTiao=res.data;
                    tiaoSizeContentSet_real();
                }
            });
        }else{
            tiaoSizeContentSet_real();
        }
    }
    function tiaoSizeContentSet_real() {
        $('.size-list').find('[name="part[]"]').each(function(i100){
            var temp=$(this).val();
            var _this=this;
            $.each(allPartTiao, function(i, n){
                if(n.name==temp){
                    //1,显示跳码规则
                   if( n.tiaoSizeContent.length==0){
                       $(_this).parent().parent().find('.tiaoSizeContent').html('-----');
                   }else{
                       var html='';
                       $.each( n.tiaoSizeContent, function(i2, n2){
                           html+=n2.min_name+'-'+n2.max_name+':'+n2.tiao_num +"<br>";
                       });
                       $(_this).parent().parent().find('.tiaoSizeContent').html(html);
                   }
                   //2,跳码规则设置
                    var tr_num = $(_this).parent().parent().prevAll().length + 1; //行号
                    n.ext0.tr_num=tr_num+'';
                    n.ext0.part=n.name;
                    n.ext0['xm_select_size[]']=n.ext0.xm_select_size;
                    n.ext0['tiao_num[]']=n.ext0.tiao_num;
                    allTiaoData[tr_num]=n.ext0;
                }
            });
        });
    }
</script>